import React from "react";
import styles from "./index.less";
import {
  Form,
  Input,
  Tooltip,
  Select,
  Button,
  message,
  Icon,
  Tabs,
  Modal,
  Row, Col, Card, Avatar
} from "antd";
import request from '@/utils/request';
import {EditOutlined, EllipsisOutlined, SettingOutlined} from '@ant-design/icons';
import router from "umi/router";
const { TabPane } = Tabs;
const {Meta} = Card;
const FormItem = Form.Item;
const formLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};
const formRef = React.createRef();
class RegistrationForm extends React.Component {
  formRef = React.createRef();
  state = {
    confirmDirty: false,
    user: {},
    visible: false
  };
  showModal = () => {
    request.post('/api/test', {
    }).then((result:Object)=>{
      console.log(result)
    })
    // this.setState({
    //   visible: true,
    // });
  };

  handleCancel = e => {
    console.log(e);
    this.setState({
      visible: false,
    });
  };
  handleSubmitPassWord = async (values: object) => {
    let {validateFields} =  formRef.current;
    validateFields().then(values=>{
      console.log(values);
      if(values.password != values.twopassword){
        message.error("两次密码不一样");
        return
      }
      request.put('/api/editpassword', {
        params: {
          id:localStorage.getItem('antd_pro_id'),
          password:values.password
        }
      }).then((result:Object)=>{
        console.log(result)
        if (result.data.success == true) {
          message.info("修改成功");
        }else{
          message.info("修改失败");
        }
        this.setState({
          visible: false,
        });
        return true;
      })
    })
  };
  getUser = async () => {
    try {
      let id: String | null = localStorage.getItem('antd_pro_id')
      let user = await request('/api/getuser', {
        method: 'GET',
        params: {
          id: id
        }
      })
      this.setState({
        user: user.data
      })
      console.log(this.state.user)
      this.formRef.current.setFieldsValue({
        ...user.data
      });
      console.log(this.formRef.current)
      return true;
    } catch (error) {
      return false;
    }
  }
  componentWillMount = async () => {
    await this.getUser();
  }

  handleSubmit = async (values: object) => {
    // e.preventDefault();
    console.log(values)
    try {
      let data: object = {
        id: localStorage.getItem('antd_pro_id'),
        mobile: values.mobile,
        email: values.email,
      }
      let result = await request('/api/useredit', {
        method: 'PUT',
        params: {
          ...data
        }
      })
      console.log(result)
      if (result.data.success == true) {
        message.info("修改成功");
        this.getUser();
      }else{
        message.info("修改失败");
      }
      return true;
    } catch (error) {
      return false;
    }
  };

  handleConfirmBlur = e => {
    const {value} = e.target;
    this.setState({confirmDirty: this.state.confirmDirty || !!value});
  };

  compareToFirstPassword = (rule, value, callback) => {
    const {form} = this.props;
    if (value && value !== form.getFieldValue("password")) {
      callback("Two passwords that you enter is inconsistent!");
    } else {
      callback();
    }
  };

  validateToNextPassword = (rule, value, callback) => {
    const {form} = this.props;
    if (value && this.state.confirmDirty) {
      form.validateFields(["confirm"], {force: true});
    }
    callback();
  };



  render() {
    const formItemLayout = {
      labelCol: {
        xs: {span: 2},
        sm: {span: 2}
      },
      wrapperCol: {
        xs: {span: 22},
        sm: {span: 22}
      }
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 8,
          offset: 0
        },
        sm: {
          span: 8,
          offset: 2
        }
      }
    };


    return (
      <Row style={{margin: 10}}>
        <Col style={{width: 300}}>
          <Card
            style={{width: 300}}
            cover={
              <img
                alt="example"
                src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
              />
            }
            actions={[
              <SettingOutlined key="setting"/>,
              <EditOutlined key="edit"/>,
              <EllipsisOutlined key="ellipsis"/>,
            ]}
          >
            <Meta
              avatar={
                <Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png"/>
              }
              title={this.state.user.username}
              description={this.state.user.student_number}
            />
          </Card>
        </Col>
        <Col span={16} style={{marginLeft:20}} className="card-container">
          <Tabs tabBarExtraContent={<Button onClick={this.showModal}>修改密码</Button>}  type="card">
            <TabPane tab="个人信息" key="1" style={{backgroundColor: '#fff',padding:20,paddingTop:30,paddingBottom:10}}>

                <Form {...formItemLayout} onFinish={this.handleSubmit}
                      ref={this.formRef}

                  // initialValues={this.state.user}
                >
                  <Form.Item label="邮箱"
                             name="email" rules={[
                    {
                      type: "email",
                      message: "The input is not valid E-mail!"
                    },
                    {
                      required: true,
                      message: "Please input your E-mail!"
                    }
                  ]}>
                    <Input/>
                  </Form.Item>
                  <Form.Item label="电话" name="mobile"
                             rules={[
                               {required: true, message: "Please input your phone number!"}
                             ]}>
                    <Input style={{width: "100%"}}/>
                  </Form.Item>
                  <Form.Item {...tailFormItemLayout}>
                    <Button type="primary" htmlType="submit">
                      修改
                    </Button>
                  </Form.Item>
                </Form>
            </TabPane>
            <TabPane tab="敬请期待" key="2">
              Content of tab 2
            </TabPane>
            <TabPane tab="敬请期待" key="3">
              Content of tab 3
            </TabPane>
          </Tabs>,
         </Col>
        <Modal
          title="Basic Modal"
          visible={this.state.visible}
          onOk={this.handleSubmitPassWord}
          onCancel={this.handleCancel}
        >
          <Form {...formLayout}
                ref={formRef}>
            <Form.Item label="密码" hasFeedback name="password"
                       rules={[
                         {
                           required: true,
                           message: "Please input your password!"
                         },
                       ]}>
              <Input.Password/>
            </Form.Item>
            <Form.Item label="确认密码" hasFeedback name="twopassword"
                       rules={[
                         {
                           required: true,
                           message: "Please input your password!"
                         },
                       ]}>
              <Input.Password/>
            </Form.Item>
          </Form>
        </Modal>
      </Row>
    );
  }
}

// const WrappedRegistrationForm = Form.create({ name: "register" })(
//   RegistrationForm
// );
const WrappedRegistrationForm = RegistrationForm;
export default () => (
  <div className={styles.container}>
    <div id="components-form-demo-register">
      <WrappedRegistrationForm/>
    </div>
  </div>
);
